package org.scratchcrew.services;

import org.scratchcrew.domain.Board;
import org.scratchcrew.domain.BoardData;
import org.scratchcrew.domain.PrivateBoard;
import org.scratchcrew.domain.User;
import org.scratchcrew.domain.dao.BoardDao;
import org.scratchcrew.domain.dao.BoardDataDao;
import org.scratchcrew.domain.dao.UserDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Implementation of {@link BoardService} interface.
 * 
 */
@Service(value = "boardService")
public class BoardServiceImpl implements BoardService {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	/**
	 * Board dao object used to access persistence.
	 */
	@Autowired
	private BoardDao boardDao;

	@Autowired
	private BoardDataDao boardDataDao;

	@Autowired
	private UserDao userDao;
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public Board create(String boardData, String name, Long ownerId) {
		Board board;
		if (ownerId == null) {
			if (logger.isInfoEnabled()) {
				logger.info(String.format(
						"Creating new public board with board data %s",
						boardData));
			}
			board = new Board();
			boardDao.save(board);
		} else if (name != null) {
			PrivateBoard privateBoard = new PrivateBoard();
			privateBoard.setName(name);
			User owner = userDao.find(ownerId);
			privateBoard.setOwner(owner);
			board = privateBoard;
		} else {
			throw new IllegalArgumentException(String.format(
					"Cannot create board with given parameters:"
							+ " boardData=%s, name=%s, ownerId=%s", boardData,
					name, ownerId));
		}
		board = boardDao.save(board);
		BoardData boardDataEntity = new BoardData();
		boardDataEntity.setBoard(board);
		boardDataEntity.setBoardData(boardData);
		boardDataEntity = boardDataDao.save(boardDataEntity);
		return board;
	}

	@Override
	public void delete(Long id) {
		Board board = boardDao.find(id);
		boardDao.delete(board);
	}

	@Override
	public Board find(Long id) {
		return boardDao.find(id);
	}

	@Override
	public BoardData findBoardData(Long boardId) {
		BoardData boardData = boardDataDao.findByBoardId(boardId);
		return boardData;
	}
}
